import { login } from '../../api/api.js';
import Util from '../../utils/util.js';

const app = getApp();
Page({

  data: {
    fields:{
      phone: { title: "手机号码",placeholder:"请输入手机号码", required: true, is_tel: true, type: "number" },
      password: { title: "密码", type: "password", placeholder:"请输入您的密码", required: true },
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    if(app.globalData.token){
      return wx.switchTab({ url: "/pages/index/index"})
    }

    this.setData({
      navHeight:  app.globalData.navHeight,
      isIphoneX: app.globalData.isIphoneX
    })

    this.initValidate();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  },

  formSubmit: function (e) {
    const that = this;
    // const form_data = e.detail.value;
  
    const pages = getCurrentPages();
    const currPage = pages[pages.length - 1];

    const phone = this.data.fields['phone'].default_val,
          password = this.data.fields['password'].default_val;

    if(!Util.checkPhone(phone))
      return app.Tips({ title: "手机号码格式错误"})

    if(!password)
      return app.Tips({ title: "密码必填"})

    wx.showLoading({ title: '正在登录...' });
    login(phone, password).then((res) => {
      wx.setStorageSync("USERINFO", JSON.stringify(res.data));
      wx.setStorageSync("TOKEN", res.data.token);
      app.globalData.userInfo = res.data
      app.globalData.token =  res.data.token

      let url = "/pages/index/index";
      let is_tab = true;

      if(currPage >= 1){
        if( ['pages/index/index','pages/staff/index','pages/article/index', 'pages/member/index'].indexOf (currPage[0].route) ){
          url = '/' + currPage[0].route
        }else{
          url = currPage[0].route
          is_tab = false;
        }
      }

      app.Tips({ title: "登录成功" , icon: 'success'});
      if(res.data.open_id && res.data.open_id != "null"){
        if(is_tab){
          wx.switchTab({ url: url })
        }else{
          wx.redirect({ url: url })
        }
        return
      }

      wx.showModal({
        title: '授权提醒',
        content: '授权后可以接受系统的订阅消息',
        cancelText: '取消',
        cancelColor: '#999999',
        confirmText: '确定',
        confirmColor: '#3CC51F',
        success: (res) => {
          if(res.confirm) {
            that.getWechatUserInfo().then( result => {
              if(is_tab){
                wx.switchTab({ url: url })
              }else{
                wx.redirect({ url: url })
              }
            }).catch( errmsg => {

              if(is_tab){
                wx.switchTab({ url: url })
              }else{
                wx.redirect({ url: url })
              }

            })
          }else{
            if(is_tab){
              wx.switchTab({ url: url })
            }else{
              wx.redirect({ url: url })
            }
          }
        }
      })

      wx.hideLoading();
    }).catch( errmsg => {
      return app.Tips({ title: errmsg });
    });
  },

  getWechatUserInfo(){
    const that = this;

    return new Promise((resolve, reject) => {
      wx.getUserProfile({
        desc: '获取你的昵称、头像用于信息注册', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        lang: 'zh_CN',
        success: ( result) => {
          wx.showLoading({ title: '正在登录' });
          Util.userRegister(result).then(result => {
            return resolve(result);
            wx.hideLoading();
          }).catch((errmsg) => {
            wx.hideLoading();
            reject(errmsg);
          });
        },
        fail: (err) => {
          reject( err );
        }
      })
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  },

  inputName (e) {
    const fields = this.data.fields;
    const id = e.currentTarget.dataset.id;
    fields[id].default_val = e.detail.value;
    this.setData({ fields: fields });
  },

  // 表单验证
  initValidate () {
    const fields = this.data.fields;
    const rules = {};
    const messages = {};

    for (const k in fields) {
      if (fields[k].required != true) {continue;}
      rules[k] = { required: true };

      if(fields[k].is_tel === true){
        rules[k].tel = true;
      }

      messages[k] = {
        required: fields[k].title + '必填'
      };
    }

    // this.WxValidate = new WxValidate(rules, messages);
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})